package com.ujson.chat.client.command;

import com.ujson.base.common.task.AsyncTask;
import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.client.builder.LoginMessageBuilder;
import com.ujson.chat.client.controller.CommandController;
import com.ujson.chat.client.session.ClientSession;
import com.ujson.chat.common.dto.UserDto;
import com.ujson.chat.common.enums.ConsoleCommandType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Scanner;

/**
 * <h3>ujson-parent</h3>
 * <p>控制台登录命令</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-22 21:25
 */
@Slf4j
@Service
public class LoginConsoleCommand extends ConsoleCommand<UserDto> {
    @Autowired
    private LoginMessageBuilder loginMessageBuilder;
    @Autowired
    private CommandController commandController;

    private String loginStrPattern = "\\S+@\\S+";

    public ConsoleCommandType getType() {
        return ConsoleCommandType.LOGIN;
    }

    @Override
    public UserDto getInput() {
        return UserDto.create(getInputString());
    }

    @Override
    public String getMatchPattern() {
        return this.loginStrPattern;
    }

    @Override
    public void exec(Scanner scanner) {
        if (commandController.getClientSession().isLogin()) {
            System.err.println("已经登录, 无需登录!");
            return ;
        }
        String tips = "未登录, 需要先登录才能进行聊天, 请登录!";
        while (!commandController.getClientSession().isLogin()) {
            System.err.println(tips);
            tips = "登录失败, 请重新登录!";
            System.err.println("请输入用户名@密码:");
            super.exec(scanner);
            LogUtil.info(log, "input: " + this.getInputString());
            doLogin();
        }
    }

    public void doLogin() {
        if (commandController.getClientSession().isLogin()) {
            LogUtil.info(log, "already login, repeat login.");
            return ;
        }
        AsyncTask.addTask(() -> {
            UserDto userDto = getInput();
            ClientSession.getClientSession(getChannel())
                    .setUserDto(userDto)
                    .getChannel()
                    .writeAndFlush(
                            loginMessageBuilder.buildLoginMessage(getChannel(), userDto)
                    );
        });
        commandController.getClientSession().waitLogin();
    }
}
